package com.example.newbeeshop;


import android.content.Context;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.constraintlayout.helper.widget.Carousel;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends Fragment {
    private String link = "http://backend-api-01.newbee.ltd/api/v1/index-infos";
    private List<Carousels> carouselsList = new ArrayList<>();
    private String change;
    private Banner banner;
    private List<Goods> newList = new ArrayList<>();
    private List<Goods> hotList = new ArrayList<>();
    private List<Goods> recommendList = new ArrayList<>();
    private String[] names = {"新峰超市", "新峰服饰","全球购","新峰生鲜","新峰到家","充值缴费","9.9元拼","领券","省钱","全部"};
    private int[] icons = {R.mipmap.chaoshi, R.mipmap.cloth,R.mipmap.gloabel,
            R.mipmap.xian,R.mipmap.tohome,R.mipmap.chong,R.mipmap.ping,
            R.mipmap.juan,R.mipmap.money, R.mipmap.all};
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 200) {
                banner.setAdapter(new BannerImageAdapter<Carousels>(carouselsList) {
                    @Override
                    public void onBindView(BannerImageHolder holder, Carousels data, int position, int size) {
                        Glide.with(holder.imageView)
                                .load(data.getCarousels())
                                .into(holder.imageView);
                        holder.imageView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(getContext(), "1111", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                }).setIndicator(new CircleIndicator(getContext()));
            }
        }
    };


    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        banner = view.findViewById(R.id.banner1);
        GridView gv_nav = view.findViewById(R.id.gv_nav);
        gv_nav.setNumColumns(5);//列数
        gv_nav.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return names.length;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = View.inflate(getContext(), R.layout.item_nav, null);
                ImageView imageView = view.findViewById(R.id.imageView);
                TextView textView = view.findViewById(R.id.textView2);
                textView.setText(names[position]);
                imageView.setImageResource(icons[position]);
                return view;
            }
        });
        gv_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(getContext(), "敬请期待", Toast.LENGTH_SHORT).show();
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(link);
                    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
                    if(cn.getResponseCode() == 200){
                        InputStream inputStream = cn.getInputStream();
                        change = stream2String(inputStream);
                        System.out.println(change);
                        JSONObject object = new JSONObject(change);
                        if(object.optInt("resultCode")==200){
                            JSONObject data = object.optJSONObject("data");
                            JSONArray carousels = data.optJSONArray("carousels");
                            for (int i = 0; i < carousels.length(); i++) {
                                JSONObject object1 = carousels.optJSONObject(i);
                                String carouselUrl = object1.optString("carouselUrl");
                                String redirectUrl = object1.optString("redirectUrl");
                                carouselsList.add(new Carousels(carouselUrl, redirectUrl));
                            }
                            JSONArray hotGoodses = data.optJSONArray("hotGoodses");
                            for (int i = 0; i < hotGoodses.length(); i++) {
                                JSONObject object1 = hotGoodses.optJSONObject(i);
                                int goodsId = object1.optInt("goodsId");
                                int sellingPrice = object1.optInt("sellingPrice");
                                String goodsName = object1.optString("goodsName");
                                String goodsIntro = object1.optString("goodsIntro");
                                String goodsCoverimg = object1.optString("goodsCoverimg");
                                String tag = object1.optString("tag");
                                hotList.add(new Goods(goodsId, goodsName, goodsIntro, goodsCoverimg, sellingPrice, tag));
                            }
                            JSONArray newGoodses = data.optJSONArray("newGoodses");
                            for (int i = 0; i < newGoodses.length(); i++) {
                                JSONObject object1 = newGoodses.optJSONObject(i);
                                int goodsId = object1.optInt("goodsId");
                                int sellingPrice = object1.optInt("sellingPrice");
                                String goodsName = object1.optString("goodsName");
                                String goodsIntro = object1.optString("goodsIntro");
                                String goodsCoverimg = object1.optString("goodsCoverimg");
                                String tag = object1.optString("tag");
                                newList.add(new Goods(goodsId, goodsName, goodsIntro, goodsCoverimg, sellingPrice, tag));
                            }
                            JSONArray recommendGoodses = data.optJSONArray("recommendGoodses");
                            for (int i = 0; i < recommendGoodses.length(); i++) {
                                JSONObject object1 = recommendGoodses.optJSONObject(i);
                                int goodsId = object1.optInt("goodsId");
                                int sellingPrice = object1.optInt("sellingPrice");
                                String goodsName = object1.optString("goodsName");
                                String goodsIntro = object1.optString("goodsIntro");
                                String goodsCoverimg = object1.optString("goodsCoverimg");
                                String tag = object1.optString("tag");
                                recommendList.add(new Goods(goodsId, goodsName, goodsIntro, goodsCoverimg, sellingPrice, tag));
                            }
                            handler.sendEmptyMessage(200);
                        }else {
                            String message = object.optString("message");
                            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        return view;
    }
//        banner=view.findViewById(R.id.banner1);
//        picList.add("https://newbee-mall.oss-cn-beijing.aliyuncs.com/images/banner-mate60.png");
//        picList.add("https://newbee-mall.oss-cn-beijing.aliyuncs.com/images/banner-matex5.png");
//        picList.add("https://newbee-mall.oss-cn-beijing.aliyuncs.com/images/banner-p60-pro-white.png");
//        banner.setAdapter(new BannerImageAdapter<String>(picList) {
//            @Override
//            public void onBindView(BannerImageHolder holder, String data, int position, int size) {
//                //网络图片加载
//                Glide.with(holder.imageView)
//                        .load(data)//获取图片URL
//                        .into(holder.imageView);
//            }
//        });
//        banner.setIndicator(new CircleIndicator(view.getContext()));
//        banner.setIndicatorRadius(80);//设置指示器圆角，不要圆角可以设置为0
//        banner.setLoopTime(3000);
//        banner.setIndicatorNormalColor(getResources().getColor(R.color.white));
//        banner.setIndicatorSelectedColor(getResources().getColor(R.color.black));
        private String stream2String(InputStream is) throws IOException {
            byte[] bytes=new byte[1024];
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int len=0;
            while((len=is.read(bytes))>0){
                baos.write(bytes,0,len);
            }
            return baos.toString();
}

}